package cn.edu.sgu.www.mhxysy.service.school.impl;

import cn.edu.sgu.www.mhxysy.entity.role.RoleAccount;
import cn.edu.sgu.www.mhxysy.entity.school.SchoolSkill;
import cn.edu.sgu.www.mhxysy.entity.school.SchoolSkillCategory;
import cn.edu.sgu.www.mhxysy.mapper.school.SchoolSkillCategoryMapper;
import cn.edu.sgu.www.mhxysy.mapper.school.SchoolSkillMapper;
import cn.edu.sgu.www.mhxysy.service.role.RoleAccountService;
import cn.edu.sgu.www.mhxysy.service.school.SchoolSkillService;
import cn.edu.sgu.www.mhxysy.util.CollectionUtils;
import cn.edu.sgu.www.mhxysy.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static cn.edu.sgu.www.mhxysy.consts.IdentifierPrefixes.PREFIX_MPJN;

/**
 * @author 沐雨橙风ιε
 * @version 1.0
 */
@Service
public class SchoolSkillServiceImpl implements SchoolSkillService {

	private final SchoolSkillMapper schoolSkillMapper;
	private final RoleAccountService roleAccountService;
	private final SchoolSkillCategoryMapper schoolSkillCategoryMapper;

	@Autowired
	public SchoolSkillServiceImpl(
			SchoolSkillMapper schoolSkillMapper,
			RoleAccountService roleAccountService,
			SchoolSkillCategoryMapper schoolSkillCategoryMapper) {
		this.schoolSkillMapper = schoolSkillMapper;
		this.roleAccountService = roleAccountService;
		this.schoolSkillCategoryMapper = schoolSkillCategoryMapper;
	}

	@Override
	public void init(String roleId) {
		// 删除角色的门派技能
		UpdateWrapper<SchoolSkill> updateWrapper = new UpdateWrapper<>();

		updateWrapper.eq("role_id", roleId);

		Long count = schoolSkillMapper.selectCount(updateWrapper);

		if (count > 0) {
			schoolSkillMapper.delete(updateWrapper);
		}

		// 查询角色信息
		RoleAccount roleAccount = roleAccountService.selectById(roleId);

		// 查询门派的所有技能
		QueryWrapper<SchoolSkillCategory> queryWrapper = new QueryWrapper<>();

		queryWrapper.eq("school_id", roleAccount.getSchoolId());

		List<SchoolSkillCategory> list = schoolSkillCategoryMapper.selectList(queryWrapper);

		// 获取当前时间生成的uuid
		String uuid = StringUtils.uuid();
		// 获取角色等级
		Integer grade = roleAccount.getGrade();

		// 批量添加门派技能
		if (CollectionUtils.isNotEmpty(list)) {
			for (SchoolSkillCategory schoolSkillCategory : list) {
				Integer categoryId = schoolSkillCategory.getId();

				// 添加门派技能
				SchoolSkill schoolSkill = new SchoolSkill();

				schoolSkill.setId(PREFIX_MPJN + uuid + categoryId);
				schoolSkill.setGrade(grade);
				schoolSkill.setRoleId(roleId);
				schoolSkill.setSkillId(categoryId);

				schoolSkillMapper.insert(schoolSkill);
			}
		}
	}

}